from notemgr import notemgr
from blockmgr import blockmgr
from tagmgr import tagmgr
import json
def dumps(state, data=''):
    return json.dumps([state, data])


def add_block(request, note_id):
    try:
        if not note_id.isdigit():
            raise TypeError, 'note_id(`%s`) is not a digit.' % note_id
    except TypeError, e:
        request.respond(dumps(500, repr(e)))
        request.done(500)
    else:
        id = blockmgr.add(note_id, '<br/>', -1);
        request.respond(dumps(200, {'id': id}))
        request.done(200)


def remove_block(request, id):
    try:
        if not id.isdigit():
            raise TypeError, 'id(%s) is not a digit' % id
        b = blockmgr.get(id)
        tagmgr.detach_all(id);
        blockmgr.remove(id)
    except TypeError, e:
        request.respond(dumps(500, repr(e)))
        request.done(500)
    else:
        request.respond(dumps(200, b.serialize()))
        request.done(200)

def save_block_content(request, id, content):
    try :
        if not id.isdigit():
            raise TypeError, 'id(`%s`) is not a digit' % id
    except Error, e:
        request.respond(dumps(500, repr(e)))
        request.done(500)
    else:
        blockmgr.modify(id, content)
        request.respond(dumps(200))
        request.done(200)

def save_block_pos(request, ordered_ids):
    ordered_ids = json.loads(ordered_ids)
    blockmgr.save_pos(ordered_ids)
    request.respond(dumps(200))
    request.done(200)

def list_block(request, note_id):
    try:
        if not note_id.isdigit():
            raise TypeError, 'note_id(`%s`) is not a digit.' % note_id
    except TypeError, e:
        request.respond(dumps(500, repr(e)))
        request.done(200)
    else:
        bs = [b.serialize() for b in blockmgr.get_by_note_id(note_id)]
        bs.sort(key = lambda x:x['pos']);
        request.respond(dumps(200, bs))
        request.done(200)


